package cn.taobaoke.restful.util;

import cn.taobaoke.restful.exception.TBKException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;

/**
 * MS Excel工厂类.
 * 根据文件名后缀返回相应的Excel处理类。
 *
 * @author yangzuo
 * @since 2017-03-29
 */
public class ExcelWorkbookFactory {

    public static final String XLS_2003 = "xls";
    public static final String XLSX_2007 = "xlsx";

    /**
     *
     * @param inputStream 输入流
     * @param filename 文件名
     * @return
     * @throws IOException
     */
    public static Workbook create(InputStream inputStream, String filename) throws IOException {
        String[] tokens = filename.split("\\.");
        if (tokens.length < 2) {
            throw new TBKException("未能识别的Excel文件名：" + filename);
        }

        String suffixLower = tokens[tokens.length-1].toLowerCase();

        if (ExcelWorkbookFactory.XLS_2003.equals(suffixLower)) {
            return new HSSFWorkbook(new POIFSFileSystem(inputStream));
        }

        if (ExcelWorkbookFactory.XLSX_2007.equals(suffixLower)) {
            return new XSSFWorkbook(inputStream);
        }

        throw new TBKException("不支持的Excel格式 [" + suffixLower + "]");
    }
}
